<template>
  <div class='container'>

    <!-- 文章分类栏 -->
    <van-tabs
      @change="changTab"
      v-model="articleIndex"
      swipeable
    >
      <van-tab
        :key="item.id"
        v-for="(item,index) in channelsList"
        :title="item.name"
      >
        <!-- 可滚动内容区域 -->
        <NewsListView
          :ref="'alist'+index"
          :channelID='item.id'
        />
      </van-tab>
    </van-tabs>
    <!-- 右侧图标 -->
    <span
      class="bar_btn"
      @click="showChannelEdit=true"
    >
      <van-icon name="wap-nav"></van-icon>
    </span>
    <ChannelsEditView
      :myChannelsList='channelsList'
      :articleIndex.sync='articleIndex'
      v-model="showChannelEdit"
    />
  </div>

</template>

<script>
import { getChannelListAPI } from '../../api/channels'
import NewsListView from './components/newsListView'
import ChannelsEditView from './components/channel-edit'
export default {
  name: 'home-index',
  data () {
    return {
      channelsList: [], // 频道列表数据
      articleIndex: 0, // tab标题的索引
      showChannelEdit: false
    }
  },
  methods: {
    async getChannelsListFn () { // 获取频道列表
      const { data } = await getChannelListAPI()
      this.channelsList = data.channels
    },
    changTab (index) { // 当 tab页 更新的时候 也要记录位置 调用子组件的方法
      this.$refs['alist' + index] && this.$refs['alist' + index][0].scrollPos()
    }
  },
  created () {
    this.getChannelsListFn()
  },
  components: {
    NewsListView,
    ChannelsEditView
  },
  activated () { // 钩子函数当该页面被访问的时候触发 当组件被缓存  这个钩子函数才能用，对应的有deactivated函数离开页面的时候触发
    // console.log()
    this.$refs['alist' + this.articleIndex] && this.$refs['alist' + this.articleIndex][0].scrollPos()
  },
  // 处理refresh_token失效，回跳缓存不刷新问题
  watch: {
    '$store.state.user.token' () {
      console.log('refresh')
      this.getChannelsListFn()
    }
  }

}
</script>

<style scoped lang='less'>
.van-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;
  // 自定义tab样式
  /deep/ .van-tabs__wrap {
    height: 36px;
    padding-right: 36px;
    .van-tab {
      line-height: 36px;
    }
    .van-tabs__line {
      background-color: #3296fa;
      height: 2px;
    }
  }
  /deep/ .van-tabs__content {
    flex: 1;
    overflow: hidden;
  }
  /deep/ .van-tab__pane {
    height: 100%;
    // 控制列表区域可滚动
    .scroll-wrapper {
      height: 100%;
      overflow-y: auto;
    }
  }
}
.bar_btn {
  width: 36px;
  height: 35px;
  position: absolute;
  top: 0;
  right: 0;
  font-size: 20px;
  text-align: center;
  line-height: 40px;
  box-shadow: -6px -6px 8px #ddd;
}
</style>
